class Item < ActiveRecord::Base
  has_many :pictures, :class_name => 'ItemPicture', :dependent => :destroy, :limit=>4
  has_many :ratings, :class_name  => 'ItemRating', :dependent => :destroy, :limit=>5
  has_many :item_tags, :dependent => :destroy
  has_many :tags, :through => :item_tags
  has_many :alliances, :class_name => 'ItemAlliance', :dependent => :destroy
  has_one :statistic, :class_name => 'ItemStatistic', :dependent => :destroy
  belongs_to :item_style, :foreign_key => :style_id
  belongs_to :brand
  belongs_to :cat1, :class_name => 'ItemCategory', :foreign_key => :cat1_id
  belongs_to :cat2, :class_name => 'ItemCategory', :foreign_key => :cat2_id
  
  has_many :user_favorite_infos, :as => :favoritable
  has_many :item_recommends, :as => :recommendable
  #has_many :user_abuse_reports, :as => :abusable
  
  validates_presence_of :name, :item_style
  validates_uniqueness_of :name
  
  STATUSES = { 0 => '默认', 1 => '上架', -2 => '下架', -1 => '删除' }
  
  FLAGS = { 0 => '默认', 1 => '热门商品', 2 => '本周人气榜', 3 => '兜兜推荐', 4 => '热门点评', 5 => '最新点评' }
  
  named_scope :valid, :conditions => ['status >= ?', 0]
  named_scope :limit, lambda { |size| { :limit => size } }
  
  { :hot => 1, :top => 2, :recommend => 3, :hot_comment => 4, :recent_comment => 5 }.each do |method_name, flag|
    named_scope method_name, :conditions => { :flag => flag }
  end
  
  named_scope :filter, lambda { |params|
    c, h = [], {}
    
    unless params[:id].blank?
      c << "id LIKE :id"
      h[:id] = "%#{params[:id]}%"
    end
    unless params[:name].blank?
      c << "name LIKE :name"
      h[:name] = "%#{params[:name]}%"
    end
    unless params[:item_status].blank?
      c << "status = :status"
      h[:status] = params[:item_status].to_i
    end
    unless params[:brand_id].blank?
      c << "brand_id = :brand_id"
      h[:brand_id] = params[:brand_id].to_i
    end
    unless params[:style_id].blank?
      c << "style_id = :style_id"
      h[:style_id] = params[:style_id].to_i
    end
    unless params[:cat1_id].blank?
      c << "cat1_id = :cat1_id"
      h[:cat1_id] = params[:cat1_id].to_i
    end
    unless params[:cat2_id].blank?
      c << "cat2_id = :cat2_id"
      h[:cat2_id] = params[:cat2_id].to_i
    end
    
    { :conditions => [c.join(' AND '), h] }
  }
  
  named_scope :picture_count, lambda {|item_id| {:select=>"count(id) as vul",:from=>:item_pictures,:conditions=>["item_id=?",item_id]}}
  named_scope :review_count, lambda {|item_id| {:select=>"count(id) as vul",:from=>:item_ratings,:conditions=>["item_id=?",item_id]}}
  
  class << self
    
    def status_options
      STATUSES.inject([]){ |arr, obj| arr << obj.reverse }
    end
    
    def flag_options
      FLAGS.inject([]){ |arr, obj| arr << obj.reverse }
    end
    
  end
  
  def to_s
    name
  end
  
  def display_status
    STATUSES[status]
  end
  
  def display_flag
    FLAGS[flag]
  end
  
  def del
    update_attributes!(:status => -1)
  end
  
end
